package com.openatc.agent.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;
import com.openatc.core.common.IErrorEnumImplOuter;
import com.openatc.core.model.RESTRetBase;
import com.openatc.core.util.GsonUtil;
import com.openatc.core.util.RESTRetUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author
 * @description
 * @modified By：验证过期时间
 * @version:
 * @date ：Created in 2024/12/6 16:34
 */
@Component
public class DateVerifyInterceptor implements HandlerInterceptor {
    private static final String secret = "kedacom.date";
    @Value("${date.token}")
    private String dateToken;
    private Algorithm algorithm = null;

    private JWTVerifier verifier = null;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 没有通过验证
        if (dateToken == null || !checkToken(dateToken)) {
            final Gson gson = GsonUtil.getInstance();
            RESTRetBase retBase = RESTRetUtils.errorObj(IErrorEnumImplOuter.E_0008.getErrorCode(), IErrorEnumImplOuter.E_0008.getErrorMsg(), null, null);
            response.getWriter().write(gson.toJson(retBase));
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


    /**
     * 验证token是否在有效期以及是否启用
     * @param token
     * @Excption AuthenticationException
     */
    public boolean checkToken(String token) {
        // 验证token是否在有效期
        DecodedJWT jwt;
        try {
            jwt = getVerifier().verify(token);
        } catch (JWTVerificationException exception) {
            jwt = null;
        }
        return jwt != null;
    }

    private synchronized JWTVerifier getVerifier() {
        if (verifier == null) {
            verifier = JWT.require(getAlgorithm()).build();
        }
        return verifier;
    }

    private synchronized Algorithm getAlgorithm() {
        if (algorithm == null) {
            algorithm = Algorithm.HMAC256(secret);
        }
        return algorithm;
    }

}
